package com.google.code.rgbgoesbetween.data.inmemory;

import java.util.HashMap;
import java.util.Map;

import android.util.Log;
import android.util.SparseArray;

import com.google.code.rgbgoesbetween.data.Datastore;
import com.google.code.rgbgoesbetween.data.Item;
import com.google.code.rgbgoesbetween.data.Profile;
import com.google.code.rgbgoesbetween.data.QueryStatus;

/**
 * The implementation of the datastore interface with a sparse array
 * (an implementation of HashMap with int keys).
 * @author Avanyali
 *
 */
public class InMemoryDatastore implements Datastore {
	private SparseArray<Profile> users = new SparseArray<Profile>();
	private Map<String, Profile> usersByName = new HashMap<String, Profile>();
	
	private SparseArray<Item> items = new SparseArray<Item>();
	
	@Override
	public Profile getAccountInfo(String username) {
		Log.e("InMemoryDatastore", String.format("username: %s ", username));
		Profile requested = usersByName.get(username);
		Log.e("InMemoryDatastore", "Found " + requested);
		Log.e("InMemoryDatastore", "All users are " + usersByName);
		if (requested == null) {
			return null;
		}
		return requested;
	}

	@Override
	public Profile createProfile(Profile profile) {
		if(users.get(profile.getId()) != null) {
			Log.e("Already have", "" + profile.getId() + " as " + users.get(profile.getId()));
			return null; //We already have this one!! Fail
		}
		Log.e("Created", "" + profile.getUsername());
		users.put(profile.getId(), profile);
		usersByName.put(profile.getUsername(), profile);
		return profile;
	}

	@Override
	public QueryStatus updateProfile(Profile profile) {
		users.put(profile.getId(), profile);
		usersByName.put(profile.getUsername(), profile);
		return QueryStatus.QUERY_SUCCESS;
	}

	@Override
	public Item createItem(Item item) {
		Log.d("INMEMORY", "Item: " + item.toString());
		items.put(item.getId(), item);
		return item;
	}

	@Override
	public QueryStatus updateItem(Item item) {
		return null;
	}

	@Override
	public QueryStatus deleteItem(Item item) {	
		return null;
	}

	@Override
	public Item requestItem(int id) {	
		return items.get(id);
	}

	@Override
	public QueryStatus deleteProfile(Profile profile)
	{
		users.remove(profile.getId());
		usersByName.remove(profile.getUsername());
		return QueryStatus.QUERY_SUCCESS;
	}

}
